﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace AngleExpress.utils
{
    public class IpFinder
    {
        private const string IPREG= @"((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}";

        public static async Task<string> GetIP()
        {
            string ip;
            ip = await SecondFind();
            if (ip != string.Empty)
                return ip;
            ip = await ThirdFind();
            if (ip != string.Empty)
                return ip;
            ip = await FourthFind();
            return ip;
        }

        private static async Task<string> HttpGetPageHtml(string url)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(url);
            string result = await response.Content.ReadAsStringAsync();
            return result;

        }

        private static async Task<string> SecondFind()
        {
            try
            {
                string html = await HttpGetPageHtml("https://ip.tool.chinaz.com/");
                string reg = "<input id=\"address\" type=\"text\" name=\"ip\" url=\"true\" value=\"(" + IPREG + ")\"";
                Match m = Regex.Match(html, reg);
                string ip = string.Empty;
                if (m.Success)
                {
                    ip = m.Groups[1].Value;
                }
                return ip;
            }
            catch (Exception e)
            {
                return "";
            }
        }

        private static async Task<string> ThirdFind()
        {
            try
            {
                string html = await HttpGetPageHtml("https://ip.lihaoba.com/");
                string reg = "您本机的本地IP：<a href=.*?>(" + IPREG + ")</a>";
                Match m = Regex.Match(html, reg);
                string ip = string.Empty;
                if (m.Success)
                {
                    ip = m.Groups[1].Value;
                }
                return ip;
            }
            catch (Exception e)
            {
                return "";
            }
        }

        private static async Task<string> FourthFind()
        {
            try
            {
                string html = await HttpGetPageHtml("https://tool.lu/ip/");
                string reg = "<p>你的外网IP地址是：(" + IPREG + ")</p>";
                Match m = Regex.Match(html, reg);
                string ip = string.Empty;
                if (m.Success)
                {
                    ip = m.Groups[1].Value;
                }
                return ip;
            }
            catch (Exception e)
            {
                return "";
            }
        }

    }
}
